<template>
  <div>
    <van-nav-bar
      title="标签管理"
      left-text="返回"
      left-arrow
      @click-left="router.go(-1)"
    />
    <div class="pl-2 pr-2 xl:w-[1200px] xl:m-auto pt-2">
      <van-tag
        class="mr-1 mb-1"
        size="large"
        closeable
        type="primary"
        v-for="item in tagList"
        :key="item.id"
        @close="closeTag(item.id)"
      >
        {{ item.label }}
      </van-tag>
      <van-tag
        @click="showDialog"
        plain
        size="large"
        type="primary"
        class="cursor-pointer"
      >
        <van-icon name="plus" />
        添加标签
      </van-tag>
    </div>
    <div>
      <!-- :before-close="beforeClose" -->
      <v-dialog
        :before-close="beforeClose"
        @cancel="cancel"
        v-model:show="show"
        title="创建标签"
        :show-cancel-button="true"
      >
        <div class="p-1">
          <van-field
            border
            label-width="70px"
            v-model="tagValue"
            label="标签名称:"
            placeholder="请输入标签名称"
          />
        </div>
      </v-dialog>
    </div>
  </div>
</template>
<script>
import { Dialog } from "vant";
import "vant/es/Dialog/style";
export default {
  components: {
    "v-dialog": Dialog.Component,
  },
};
</script>
<script setup>
import { Toast } from "vant";
import "vant/es/toast/style";
import router from "@/router";
import { ref } from "vue";
import { getTags, tagCreate, delTag } from "@/api/tags.js";
const tagList = ref([]);
const tagValue = ref();
const show = ref(false);

const cancel = () => {
  tagValue.value = "";
  show.value = false;
};
const closeTag = (id) => {
  delTag({ id }).then((res) => {
    Toast.success("删除成功");
    getTagsList();
  });
};
const beforeClose = (action) => {
  new Promise((resolve) => {
    if (action === "confirm") {
      if (!tagValue.value) {
        Toast("请输入标签名称");
        resolve(false);
        return;
      }
      tagCreate({
        label: tagValue.value,
      }).then((res) => {
        show.value = false;
        tagValue.value = "";
        Toast.success("添加成功");
        getTagsList();
        resolve(true);
      });
    } else {
      resolve(true);
    }
  });
};
const showDialog = () => {
  show.value = true;
};

const getTagsList = () => {
  getTags().then((res) => {
    tagList.value = res;
  });
};
getTagsList();
</script>

<style lang="scss" scoped>
</style>